<?php

/**
 * alltosun.com 商家下的单列表
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 高昂 (gaoa@alltosun.com) $
 * $Date: 2016-3-5 下午1:51:18 $
 * $Id: $
 */
class Action
{
    private $per_page = 30;

    /**
     * 显示订单列表
     */
    public function index() {

        $service_dealer = $page_no = $status = $progress = $task_user_id = $type = $search_filter = $is_excel = $store_type = $delivery_note_status = null;

        extract(URLTracker::init(array(
            'page_no' => '1',
            'status' => '1',
            'progress' => '-1',
            'task_user_id' => '-1',
            'type' => '5',
            'search_filter' => array(),
            'is_excel' => '0',
            'store_type' => '-1',
            'delivery_note_status' => -1,
            'exchange_type' => '',
            'service_dealer' => 0,
        )));

        // 拼装搜索条件
        $filter = array();

        if (isset($search_filter['id']) && $search_filter['id']) {
            $filter['id'] = $search_filter['id'];
        }

        if ($store_type != -1) {
            $order_branch_ids = _model('order_branch')->getFields('order_id', array('store_type' => $store_type));
            $filter['id'] = $order_branch_ids;
        }

        if (isset($search_filter['order_code']) && $search_filter['order_code']) {
            $decoded_id = order_helper::order_id_decode($search_filter['order_code']);
            if (is_numeric($decoded_id)) {
                $filter['id'] = $decoded_id;
            }
        }

        if (isset($delivery_note_status)) {
            switch ($delivery_note_status) {
                case -2:
                    $filter['delivery_note_status >='] = 0;
                    break;
                case -1:
                    break;
                default:
                    $filter['delivery_note_status'] = $delivery_note_status;
                    break;
            }
        }

        // 获取当前登录人的角色
        $role_id = user_helper::get_admin_role_id();
        if (!user_helper::is_all_can_show($role_id)) {
            $stype = array();
            if ($store_type != -1) {
                $stype = array($store_type);
            }
            $filter['store_id'] = store_helper::get_store_ids_by_admin_user($stype);
            if (!$filter['store_id']) {
                $filter['store_id'] = -1;
            }
        }

        $filter['is_enable'] = 1;

        if (isset($search_filter['store_user_name']) && $search_filter['store_user_name']) {
            $user_ids = user_helper::get_user_ids_by_mobile($search_filter['store_user_name']);
            $filter['user_id'] = $user_ids;
        }

        if (isset($search_filter['agency_realname']) && $search_filter['agency_realname']) {
            $user_ids = user_helper::get_user_ids_by_realname($search_filter['agency_realname']);
            $filter['agency_id'] = $user_ids;
        }

        if (isset($search_filter['agency_user_name']) && $search_filter['agency_user_name']) {
            $user_ids = user_helper::get_user_ids_by_mobile($search_filter['agency_user_name']);
            $filter['agency_id'] = $user_ids;
        }

        // 下单时间
        if (isset($search_filter['start_date_add']) && $search_filter['start_date_add']) {
            $filter['add_time >='] = $search_filter['start_date_add'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_add']) && $search_filter['end_date_add']) {
            $filter['add_time <='] = $search_filter['end_date_add'] . ' 23:59:59';
        }

        // 到货时间
        if (isset($search_filter['start_date_receiver']) && $search_filter['start_date_receiver']) {
            $filter['receiver_time >='] = $search_filter['start_date_receiver'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_receiver']) && $search_filter['end_date_receiver']) {
            $filter['receiver_time <='] = $search_filter['end_date_receiver'] . ' 23:59:59';
        }

        // 支付时间
        if (isset($search_filter['start_date_pay']) && $search_filter['start_date_pay']) {
            $filter['pay_time >='] = $search_filter['start_date_pay'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_pay']) && $search_filter['end_date_pay']) {
            $filter['pay_time <='] = $search_filter['end_date_pay'] . ' 23:59:59';
        }

        if (isset($progress) && $progress != '-1') {
            $filter['progress'] = intval($progress);
        }

        if ($status != -1) {
            $filter['status'] = $status;
        }

        // 代理
        if ($task_user_id == 1) {
            $filter['task_user_id > '] = 0;
        } else {
            if ($task_user_id == 0) {
                $filter['task_user_id'] = 0;
            }
        }

        if ($progress != '-1' || $status == 0) {
            $filter['status'] = $status;
        }

        // 兑换
        if (isset($exchange_type) && $exchange_type != '') {
            switch ($exchange_type) {
                case 'bbcoin':
                    // 抱抱币兑换
                    $filter['pay_bbcoin >'] = 0;
                case 'all':
                    // 包含兑换
                    $filter['exchange_num >'] = 0;
                    break;
            }
        }

        // added type filter by ninghx 用来区分总部订单、经销商订单还是影院订单
        if (isset($type) && $type) {
            $filter['type'] = $type;
        }

        if (isset($service_dealer) && $service_dealer != 0) {
            $filter['original_agency_id > '] = 0;
        }

        if (empty($filter)) {
            $filter['1'] = 1;
        }

        $order_list = array();
        if (count($filter)) {
            $order_count = _model('order')->getTotal(enable_filter($filter));
            if ($order_count) {
                $pager = new Pager($this->per_page);
                if ($pager->generate($order_count)) {
                    Response::assign('pager', $pager);
                }
                $order_by = ' ORDER BY `id` DESC ';
                if (!$is_excel) {
                    $order_by .= $pager->getLimit($page_no);
                }
                $order_list = _model('order')->getList(enable_filter($filter), $order_by);

                $order_list = order_helper::decorator_order_model($order_list);

                if ($is_excel) {
                    if (isset($filter['add_time >=']) && isset($filter['add_time <='])) {
                        $order_export = order_helper::decorator_order_export($order_list);
                        $this->export_excel($order_export, '商家订单');
                    } else {
                        Response::flush();
                    }
                }
                Response::assign('count', $order_count);
            }
        }

        // $express_list = _model('express')->getList(array('status'=>1));

        // $express_list = array();

        Response::assign('role_id', $role_id);
        // Response::assign('express_list', $express_list);
        Response::assign('order_list', $order_list);
        Response::assign('status', $status);
        // Response::assign('progress', $progress);
        // Response::assign('task_user_id', $task_user_id);
        // Response::assign('delivery_note_status', $delivery_note_status);

        // Response::assign('type', $type);
        // Response::assign('store_type', $store_type);
        // Response::assign('search_filter', $search_filter);

        Response::display('admin/store_order_list.html');
    }

    public function delivery_preview() {

        $page_no = $status = $progress = $task_user_id = $type = $search_filter = $is_excel = $store_type = $delivery_note_status = $is_ious = $pay_user_money = $exchange_num = null;

        extract(URLTracker::init(array(
            'page_no' => '1',
            'status' => '1',
            'progress' => '-1',
            'task_user_id' => '-1',
            'type' => '5',
            'search_filter' => array(),
            'is_excel' => '0',
            'store_type' => '-1',
            'delivery_note_status' => -1,
            'is_ious' => -1,
            'pay_user_money' => -1,
            'exchange_num' => -1,
        )));

        $filter = array();
        $filter['is_enable'] = 1;

        if ($store_type != -1) {
            $order_branch_ids = _model('order_branch')->getFields('order_id', array('store_type' => $store_type));
            $filter['id'] = $order_branch_ids;
        }

        if (isset($search_filter['order_code']) && $search_filter['order_code']) {
            $decoded_id = order_helper::order_id_decode($search_filter['order_code']);
            if (is_numeric($decoded_id)) {
                $filter['id'] = $decoded_id;
            }
        }

        if (isset($delivery_note_status)) {
            switch ($delivery_note_status) {
                case -1:
                    $filter['delivery_note_status <'] = 2;
                    break;
                default:
                    $filter['delivery_note_status'] = $delivery_note_status;
                    break;
            }
        }

        if ($is_ious != -1) {
            $filter['is_ious'] = $is_ious;
        }

        if ($pay_user_money != -1) {
            $operator = $pay_user_money > 0 ? '>' : '=';
            $filter['pay_user_money ' . $operator] = 0.00;
        }

        if ($exchange_num != -1) {
            $operator = $exchange_num > 0 ? '>=' : '<';
            $filter['exchange_num ' . $operator] = 1;
        }

        // 获取当前登录人的角色
        $role_id = user_helper::get_admin_role_id();
        if (!user_helper::is_all_can_show($role_id)) {
            $stype = array();
            if ($store_type != -1) {
                $stype = array($store_type);
            }
            $filter['store_id'] = store_helper::get_store_ids_by_admin_user($stype);
            if (!$filter['store_id']) {
                $filter['store_id'] = -1;
            }
        }

        if (isset($search_filter['user_name']) && $search_filter['user_name']) {
            $user_ids = user_helper::get_user_ids_by_mobile($search_filter['user_name']);
            $filter['user_id'] = $user_ids;
        }

        if (isset($search_filter['start_date_add']) && $search_filter['start_date_add']) {
            $filter['add_time >='] = $search_filter['start_date_add'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_add']) && $search_filter['end_date_add']) {
            $filter['add_time <='] = $search_filter['end_date_add'] . ' 23:59:59';
        }
        if (isset($progress) && $progress != '-1') {
            $filter['progress'] = intval($progress);
        }

        if ($status != -1) {
            $filter['status'] = $status;
        }

        if (isset($type) && $type) {
            $filter['type'] = $type;
        }

        if (empty($filter)) {
            $filter['1'] = 1;
        }

        $order_list = array();
        $order_count = _model('order')->getTotal(enable_filter($filter));
        if ($order_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($order_count)) {
                Response::assign('pager', $pager);
            }
            $order_by = ' ORDER BY `id` DESC ';
            if (!$is_excel) {
                $order_by .= $pager->getLimit($page_no);
            }
            $order_list = _model('order')->getList(enable_filter($filter), $order_by);

            $order_list = order_helper::decorator_order_model($order_list);

            if ($is_excel) {
                if (isset($filter['add_time >=']) && isset($filter['add_time <='])) {
                    $order_export = order_helper::decorator_order_export($order_list);
                    $this->export_excel($order_export, '送货单预审信息');
                } else {
                    Response::flush();
                }
            }
            Response::assign('count', $order_count);
        }

        $express_list = array();

        Response::assign('role_id', $role_id);
        Response::assign('express_list', $express_list);
        Response::assign('order_list', $order_list);
        Response::assign('status', $status);
        Response::assign('progress', $progress);
        Response::assign('task_user_id', $task_user_id);
        Response::assign('delivery_note_status', $delivery_note_status);

        Response::assign('type', $type);
        Response::assign('store_type', $store_type);
        Response::assign('search_filter', $search_filter);
        Response::assign('page_title', '送货单预审');
        Response::assign('page_url', 'order/admin/store_order/delivery_preview');

        Response::display('admin/delivery_note.html');
    }

    public function delivery_verify() {

        $page_no = $status = $progress = $task_user_id = $type = $search_filter = $is_excel = $store_type = $delivery_note_status = $is_ious = $pay_user_money = $exchange_num = null;

        extract(URLTracker::init(array(
            'page_no' => '1',
            'status' => '1',
            'progress' => '-1',
            'task_user_id' => '-1',
            'type' => '5',
            'search_filter' => array(),
            'is_excel' => '0',
            'store_type' => '-1',
            'delivery_note_status' => 5,
            'is_ious' => -1,
            'pay_user_money' => -1,
            'exchange_num' => -1,
        )));

        $filter = array();
        $filter['is_enable'] = 1;

        if ($store_type != -1) {
            $order_branch_ids = _model('order_branch')->getFields('order_id', array('store_type' => $store_type));
            $filter['id'] = $order_branch_ids;
        }

        if (isset($search_filter['order_code']) && $search_filter['order_code']) {
            $decoded_id = order_helper::order_id_decode($search_filter['order_code']);
            if (is_numeric($decoded_id)) {
                $filter['id'] = $decoded_id;
            }
        }

        if (isset($delivery_note_status)) {
            $filter['delivery_note_status'] = $delivery_note_status;
        }

        if ($is_ious != -1) {
            $filter['is_ious'] = $is_ious;
        }

        if ($pay_user_money != -1) {
            $operator = $pay_user_money > 0 ? '>' : '=';
            $filter['pay_user_money ' . $operator] = 0.00;
        }

        if ($exchange_num != -1) {
            $operator = $exchange_num > 0 ? '>=' : '<';
            $filter['exchange_num ' . $operator] = 1;
        }

        // 获取当前登录人的角色
        $role_id = user_helper::get_admin_role_id();
        if (!user_helper::is_all_can_show($role_id)) {
            $stype = array();
            if ($store_type != -1) {
                $stype = array($store_type);
            }
            $filter['store_id'] = store_helper::get_store_ids_by_admin_user($stype);
            if (!$filter['store_id']) {
                $filter['store_id'] = -1;
            }
        }
        //        $role_id = user_helper::get_admin_role_id();
        //        if (user_config::ASSISTANT == $role_id) {
        //            // 获取此助理的所有经销商的订单
        //            $dealer_ids = user_helper::get_assistant_dealer_ids();
        //            if ($dealer_ids && is_array($dealer_ids)) {
        //                $filter['agency_id'] = $dealer_ids;
        //            }
        //        }

        if (isset($search_filter['user_name']) && $search_filter['user_name']) {
            $user_ids = user_helper::get_user_ids_by_mobile($search_filter['user_name']);
            $filter['user_id'] = $user_ids;
        }

        if (isset($search_filter['start_date_add']) && $search_filter['start_date_add']) {
            $filter['add_time >='] = $search_filter['start_date_add'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_add']) && $search_filter['end_date_add']) {
            $filter['add_time <='] = $search_filter['end_date_add'] . ' 23:59:59';
        }
        if (isset($progress) && $progress != '-1') {
            $filter['progress'] = intval($progress);
        }

        if ($status != -1) {
            $filter['status'] = $status;
        }

        if (isset($type) && $type) {
            $filter['type'] = $type;
        }

        if (empty($filter)) {
            $filter['1'] = 1;
        }

        $order_list = array();
        $order_count = _model('order')->getTotal(enable_filter($filter));
        if ($order_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($order_count)) {
                Response::assign('pager', $pager);
            }
            $order_by = ' ORDER BY `id` DESC ';
            if (!$is_excel) {
                $order_by .= $pager->getLimit($page_no);
            }
            $order_list = _model('order')->getList(enable_filter($filter), $order_by);

            $order_list = order_helper::decorator_order_model($order_list);

            if ($is_excel) {
                if (isset($filter['add_time >=']) && isset($filter['add_time <='])) {
                    $order_export = order_helper::decorator_order_export($order_list);
                    $this->export_excel($order_export, '送货单审核信息');
                } else {
                    Response::flush();
                }
            }
            Response::assign('count', $order_count);
        }

        $express_list = array();

        Response::assign('role_id', $role_id);
        Response::assign('express_list', $express_list);
        Response::assign('order_list', $order_list);
        Response::assign('status', $status);
        Response::assign('progress', $progress);
        Response::assign('task_user_id', $task_user_id);
        Response::assign('delivery_note_status', $delivery_note_status);

        Response::assign('type', $type);
        Response::assign('store_type', $store_type);
        Response::assign('search_filter', $search_filter);
        Response::assign('page_title', '送货单审核(余额下发)');
        Response::assign('page_url', 'order/admin/store_order/delivery_verify');

        Response::display('admin/delivery_note.html');
    }

    public function delivery_payback() {

        $page_no = $status = $progress = $task_user_id = $type = $search_filter = $is_excel = $store_type = $delivery_note_status = $is_ious = $pay_user_money = $exchange_num = null;

        extract(URLTracker::init(array(
            'page_no' => '1',
            'status' => '1',
            'progress' => '-1',
            'task_user_id' => '-1',
            'type' => '5',
            'search_filter' => array(),
            'is_excel' => '0',
            'store_type' => '-1',
            'delivery_note_status' => 2,
            'is_ious' => -1,
            'pay_user_money' => -1,
            'exchange_num' => -1,
        )));

        $filter = array();
        $filter['is_enable'] = 1;

        if ($store_type != -1) {
            $order_branch_ids = _model('order_branch')->getFields('order_id', array('store_type' => $store_type));
            $filter['id'] = $order_branch_ids;
        }

        if (isset($search_filter['order_code']) && $search_filter['order_code']) {
            $decoded_id = order_helper::order_id_decode($search_filter['order_code']);
            if (is_numeric($decoded_id)) {
                $filter['id'] = $decoded_id;
            }
        }

        if (isset($delivery_note_status)) {
            $filter['delivery_note_status'] = $delivery_note_status;
        }

        if ($is_ious != -1) {
            $filter['is_ious'] = $is_ious;
        }

        if ($pay_user_money != -1) {
            $operator = $pay_user_money > 0 ? '>' : '=';
            $filter['pay_user_money ' . $operator] = 0.00;
        }

        if ($exchange_num != -1) {
            $operator = $exchange_num > 0 ? '>=' : '<';
            $filter['exchange_num ' . $operator] = 1;
        }

        // 获取当前登录人的角色
        $role_id = user_helper::get_admin_role_id();
        if (!user_helper::is_all_can_show($role_id)) {
            $stype = array();
            if ($store_type != -1) {
                $stype = array($store_type);
            }
            $filter['store_id'] = store_helper::get_store_ids_by_admin_user($stype);
            if (!$filter['store_id']) {
                $filter['store_id'] = -1;
            }
        }
        $condition = array();
        //合伙人信息
        if (isset($search_filter['agency_name']) && $search_filter['agency_name']) {
            $condition['`realname` LIKE '] = '%' . $search_filter['agency_name'] . '%';
        }
        if (isset($search_filter['agency_mobile']) && $search_filter['agency_mobile']) {
            $condition['`mobile` LIKE '] = '%' . $search_filter['agency_mobile'] . '%';
        }
        if ($condition) {
            $agency_ids = _model('user')->getFields('id', $condition);
            $filter['agency_id'] = empty($agency_ids) ? 0 : $agency_ids;
        }
        //店铺名称
        if (isset($search_filter['store_name']) && $search_filter['store_name']) {
            $store_name['`title` LIKE '] = '%' . $search_filter['store_name'] . '%';
            $store_ids = _model('store')->getFields('id', $store_name);
            $filter['store_id'] = empty($store_ids) ? 0 : $store_ids;
        }
        //掌柜手机号
        if (isset($search_filter['user_mobile']) && $search_filter['user_mobile']) {
            $user_mobile['`mobile` LIKE '] = '%' . $search_filter['user_mobile'] . '%';
            $user_ids = _model('user')->getFields('id', $user_mobile);
            $filter['user_id'] = empty($user_ids) ? 0 : $user_ids;
        }

        if (isset($search_filter['start_date_add']) && $search_filter['start_date_add']) {
            $filter['add_time >='] = $search_filter['start_date_add'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_add']) && $search_filter['end_date_add']) {
            $filter['add_time <='] = $search_filter['end_date_add'] . ' 23:59:59';
        }
        if (isset($progress) && $progress != '-1') {
            $filter['progress'] = intval($progress);
        }

        if ($status != -1) {
            $filter['status'] = $status;
        }

        if (isset($type) && $type) {
            $filter['type'] = $type;
        }

        if (empty($filter)) {
            $filter['1'] = 1;
        }

        $order_list = array();
        $order_count = _model('order')->getTotal(enable_filter($filter));
        if ($order_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($order_count)) {
                Response::assign('pager', $pager);
            }
            $order_by = ' ORDER BY `update_time` DESC ';
            if (!$is_excel) {
                $order_by .= $pager->getLimit($page_no);
            }
            $order_list = _model('order')->getList(enable_filter($filter), $order_by);

            $order_list = order_helper::decorator_order_model($order_list);

            if ($is_excel) {
                if (isset($filter['add_time >=']) && isset($filter['add_time <='])) {
                    $order_export = order_helper::decorator_order_export($order_list);
                    $this->export_excel($order_export, '回款确认信息');
                } else {
                    Response::flush();
                }
            }
            Response::assign('count', $order_count);
        }

        $express_list = array();

        Response::assign('role_id', $role_id);
        Response::assign('express_list', $express_list);
        Response::assign('order_list', $order_list);
        Response::assign('status', $status);
        Response::assign('progress', $progress);
        Response::assign('task_user_id', $task_user_id);
        Response::assign('delivery_note_status', $delivery_note_status);

        Response::assign('type', $type);
        Response::assign('store_type', $store_type);
        Response::assign('search_filter', $search_filter);
        Response::assign('page_title', '回款确认(抱抱币下发)');
        Response::assign('page_url', 'order/admin/store_order/delivery_payback');

        Response::display('admin/delivery_note.html');
    }

    /**
     * 商家订单确认送达
     */
    public function finish_store_order() {
        $order_id = Request::getParam('id', 0);
        if (!$order_id) {
            return '订单ID未知';
        }

        $order_no = order_helper::order_id_encode($order_id, 5);

        $result = _widget('order')->confirm_order_progress($order_no);

        if ($result['flag']) {
            return array('操作成功', '', AnUrl('order/admin/store_order/index'));
        } else {
            return array('$result["info"]', 'error', AnUrl('order/admin/store_order/index'));
        }
    }

    /**
     * [Excel 报表导出]
     * @param  [array] $table_data [description]
     * @return [type]             [description]
     */
    private function export_excel($table_data, $filename) {
        //获取Excel对象
        list($excelObj, $excelWriter) = _widget('tools.excel')->getExcelObj();

        $title = order_config::$order_export_column;
        //设置title
        $titleFlag = 0;
        $row_index = 2;
        foreach ($title as $title_name => $title_value) {
            $column_title_name = tools_helper::excel_column_encode($titleFlag);
            if ($titleFlag === 0) {
                $excelObj->getColumnDimension($column_title_name)->setWidth(8);
            } elseif ($title_name == 'order_time' || $title_name == 'order_pay_time') {
                $excelObj->getColumnDimension($column_title_name)->setWidth(20);
            } elseif ($title_name == 'receiver') {
                $excelObj->getColumnDimension($column_title_name)->setWidth(20);
                $excelObj->getDefaultRowDimension()->setRowHeight(25);
            } elseif ($title_name == 'cup_type') {
                $excelObj->getColumnDimension($column_title_name)->setWidth(12);
            } else {
                $excelObj->getColumnDimension()->setWidth(15);
            }

            //设置string类型
            $excelObj->getStyle($column_title_name)->getNumberFormat()->setFormatCode("@");
            $excelObj->setCellValue($column_title_name . '1', $title_value);
            $excelObj->getStyle($column_title_name)->getAlignment()->setWrapText(true);
            $titleFlag++;
        }
        $cellIndex = array('A', 'B', 'C', 'D', 'E', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X');
        //设置单元格
        foreach ($table_data as $order_key => $order) {
            $merge_cnt = count($order['goods_info']);
            if ($order_key == 0) {
                $cell_merge_index = $row_index;
            }
            $cell_index = $row_index + $order_key;

            if ($merge_cnt > 1) {
                foreach ($cellIndex as $cell) {
                    $cell_merge_flag = $cell . $cell_merge_index . ":$cell" . ($cell_merge_index + $merge_cnt - 1);
                    $excelObj->mergeCells($cell_merge_flag);
                }
            }

            //填充数据
            $excelObj->setCellValue('A' . $cell_merge_index, $order['order_id']);
            $excelObj->setCellValue('B' . $cell_merge_index, $order['id']);
            $excelObj->setCellValue('C' . $cell_merge_index, $order['order_time']);
            $excelObj->setCellValue('D' . $cell_merge_index, $order['order_status']);
            $excelObj->setCellValue('E' . $cell_merge_index, $order['order_type']);
            $excelObj->setCellValue('L' . $cell_merge_index, $order['total_amount']);
            $excelObj->setCellValue('M' . $cell_merge_index, $order['order_price']);
            $excelObj->setCellValue('N' . $cell_merge_index, $order['pay_price']);
            $excelObj->setCellValue('O' . $cell_merge_index, $order['order_pay_type']);
            $excelObj->setCellValue('P' . $cell_merge_index, $order['order_pay_time']);
            $excelObj->setCellValue('Q' . $cell_merge_index, $order['partner_name']);
            $excelObj->setCellValue('R' . $cell_merge_index, $order['partner_phone']);
            $excelObj->setCellValue('S' . $cell_merge_index, $order['store_id']);
            $excelObj->setCellValue('T' . $cell_merge_index, $order['store_name']);
            $excelObj->setCellValue('U' . $cell_merge_index, $order['store_addr']);
            $excelObj->setCellValue('V' . $cell_merge_index, $order['store_owner']);
            $excelObj->setCellValue('W' . $cell_merge_index, $order['receiver']);
            $excelObj->setCellValue('X' . $cell_merge_index, $order['order_delivery_status']);

            //填充商品信息
            foreach ($order['goods_info'] as $goods_key => $goods) {
                $goods_index = $cell_merge_index + $goods_key;
                $excelObj->setCellValue('F' . $goods_index, $goods['goods_name']);
                $excelObj->setCellValue('G' . $goods_index, $goods['cup_type']);
                $excelObj->setCellValue('H' . $goods_index, $goods['exchange_amount']);
                $excelObj->setCellValue('I' . $goods_index, $goods['exchange_total_price']);
                $excelObj->setCellValue('J' . $goods_index, $goods['amount']);
                $excelObj->setCellValue('K' . $goods_index, $goods['price']);
            }
            $cell_merge_index += $merge_cnt;
        }

        $filename = date('Y-m-d') . $filename;

        return _widget('tools.excel')->download($excelWriter, $filename);
    }
    /**
     * 用户订单表
     */
    /*
    public function export_excel($list = array()) {
        //初始化excel对象
        $objPHPExcel = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        //设置当前的sheet索引，用于后续的内容操纵
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();
        // 哪几列
        $col_arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M');
        // 第一排的标题
        $col_title_arr = array(
            '序号',
            '订单编号',
            '商品名称',
            '单价',
            '实际支付',
            '商品数量',
            '总数量',
            '总价',
            '商家信息',
            '杯型信息(杯)',
            '订单类型',
            '订单状态',
            '支付方式'
        );
        $col_content_arr = array(
            'number',
            'order_id',
            'goods_title',
            'goods_price',
            'real_price',
            'goods_num',
            'sum',
            'price',
            'store_info',
            'cup_info',
            'order_type',
            'progress',
            'pay_type'
        );
        // 设置文档属性
        foreach ($col_arr as $k => $v) {
            //设置4个列的宽度
            if (in_array($v, array('A'))) {
                $objActSheet->getColumnDimension($v)->setWidth(8);
            } else {
                $objActSheet->getColumnDimension($v)->setWidth(20);
            }
            //设置单位格内容A1,B1,C1,D1
            $objActSheet->setCellValue($v . "1", $col_title_arr[$k]);
            //格式化数字为字符串，避免导致数字默认右对齐单元格
            $objActSheet->getStyle($v)->getNumberFormat()->setFormatCode("@");
            //设置自动换行
            $objActSheet->getStyle($v)->getAlignment()->setWrapText(true);
        }

        // 填充单元格
        $key = 2;
        $mergeArr = array('A', 'B', 'G', 'H', 'I', 'J', 'K', 'L', 'M');
        foreach ($list as $k => $v) {
            $mergeCells = count($v['order_relation']);
            if ($mergeCells > 1) {
                $objActSheet->mergeCells('A' . $key . ':A' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('B' . $key . ':B' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('G' . $key . ':G' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('H' . $key . ':H' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('I' . $key . ':I' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('J' . $key . ':J' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('K' . $key . ':K' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('L' . $key . ':L' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('M' . $key . ':M' . ($key + $mergeCells - 1));
            }

            $order_type_list = order_config::$order_type;
            $cup_name_list = cup_config::$cup_type;
            $pay_type_list = order_config::$pay_type;
            $order_progress = order_config::$store_progress;
            // 先将合并的信息填入excl
            foreach ($col_arr as $k2 => $v2) {
                $place = $v2 . $key;
                $col_content = $col_content_arr[$k2];
                if (!in_array($v2, $mergeArr)) {
                    continue;
                }

                $value = '';
                if ($col_content == 'order_id') {
                    $value = ' ' . order_helper::order_id_encode($v['id']);
                } elseif ($col_content == 'price') {
                    $value = ' ' . $v['price'];
                } elseif ($col_content == 'pay_type') {
                    $value = $pay_type_list[$v['pay_type']];
                } elseif ($col_content == 'sum') {
                    //订单总商品数
                    $value = ' ' . $v['goods_num'];
                } elseif ($col_content == 'store_info') {
                    // 商家信息
                    $user_info = user_helper::get_user_info($v['user_id']);
                    $value = "收货人：" . $user_info['realname'] . "\r手机号码：" . $user_info['mobile'];
                } elseif ($col_content == 'cup_info') {
                    // 杯型信息
                    $cup_list_info = cup_helper::get_order_cup_data($v['id']);
                    if (!$cup_list_info) {
                        $value = '没有散装商品';
                    } else {
                        $value = '';
                        foreach ($cup_list_info as $cup_k => $cup_v) {
                            $value .= $cup_name_list[$cup_v['cup_type']] . '：' . $cup_v['true_cup_num'] . "\r";
                        }
                    }
                } elseif ($col_content == 'order_type') {
                    $value = $order_type_list[$v['type']];
                } elseif ($col_content == 'progress') {
                    $value = $order_progress[$v['progress']];
                } elseif ($col_content == 'number') {
                    $value = $k + 1;
                }

                $objActSheet->setCellValue($place, $value);
            }
            foreach ($v['order_relation'] as $r_k => $order_relation_info) {
                $num = $key + $r_k;
                $goods_info = goods_helper::get_goods_info($order_relation_info['goods_id']);
                $goods_title = $goods_info['title'];
                $goods_price = $order_relation_info['goods_price'];
                $goods_num = $order_relation_info['goods_num'];
                $real_price = $order_relation_info['real_price'];
                $objActSheet->setCellValue('C' . $num, $goods_title);
                $objActSheet->setCellValue('D' . $num, ' ' . $goods_price);
                $objActSheet->setCellValue('E' . $num, $real_price);
                $objActSheet->setCellValue('F' . $num, $goods_num);
            }

            if ($mergeCells > 1) {
                $key += $mergeCells;
            } else {
                $key++;
            }

            usleep(1000);
        }

        //设置页面类型
        header("Content-Type: application/vnd.ms-excel");
        //用于下载的文件头
        header("Content-Type: application/force-download");
        header("Content-Type: application/download");
        header("Content-Type: application/octet-stream");

        //$title = trim($catebirthday_gift_recordry_name."表").".xls";
        $title = date('Y-m-d') . "订单信息.xls";
        // ff正常，ie不正常，下面是从网站找到的解决方案
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
            $title = rawurlencode($title);
        }
        header("Content-Disposition: attachment; filename=" . $title);
        header("Content-Transfer-Encoding: binary");
        //最后修改时间
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        //不使用缓存
        header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: public');
        header("Expires: 0");
        header("Pragma: public");
        $objWriter->save('php://output');
        exit;
    }*/

    /**
     * AJAX 获取合伙人列表
     */
    public function ajax_get_service_dealers_list() {
        $dealer_info = user_helper::get_all_dealers_info();
        foreach ($dealer_info as $key => $item) {
            $dealer_info[$key] = parse_param(array(
                'id' => '',
                'realname' => '',
                'mobile' => '',
            ), $item);
        }
        return_data(0, 'success', $dealer_info);
    }

    /**
     * AJAX 获取合伙人列表
     */
    public function ajax_set_service_dealers() {
        $order_id = an_request('order_id', 0);
        $service_agency_id = an_request('service_agency_id', 0);

        if ($order_id == 0) {
            return_data(1, '未知的订单');
        }

        if ($service_agency_id == 0) {
            return_data(1, '未指定合伙人');
        }

        $ret = order_helper::set_order_service_agency($order_id, $service_agency_id);
        if ($ret === true) {
            return_data(0, '操作成功');
        }

        return_data(1, '操作失败' . (string)$ret);
    }

    public function ajax_get_order_detail() {
        $order_id = an_request('order_id', 0);
        if ($order_id == 0) {
            return_data(1, '未知的订单');
        }

        $order_info = order_helper::get_order_detail($order_id);

        $order_info = order_helper::decorator_order_model(array($order_info))[0];

        return_data(0, 'success', $order_info);
    }


    /**
     * 送货单审批
     *
     * @throws AnException
     */
    public function ajax_delivery_note_verify() {

        $P = array();

        $P['order_id'] = an_request('order_id', 0);
        $P['delivery_status'] = an_request('delivery_status');
        $P['reject_reason'] = an_request('reject_reason');
        $P['action'] = an_request('action');
        $P['changed_bbcoin'] = an_request('changed_bbcoin');
        $P['changed_reason'] = trim(an_request('changed_reason'));

        if (!$P['action']) {
            return_data(1, '无任何操作!');
        }

        if (!$P['order_id']) {
            return_data(1, '订单编号错误');
        }

        $order_detail = _model('order')->getList(array('id' => $P['order_id']));
        if (count($order_detail)) {
            $order_detail = array_shift($order_detail);
        }
        $order_delivery_note = order_helper::get_order_delivery_note_info_by_order_id($P['order_id']);

        if ($P['delivery_status'] != $order_delivery_note['status']) {
            return_data(1, '送货单状态已变更，请刷新页面');
        }

        $set_delivery = array();
        $set_order = array();

        switch ($P['action']) {
            case 'preview':
                // 预审
                if ($order_delivery_note['status'] === '1') {
                    $set_delivery['status'] = 5;
                    _model('order')->update(array('id' => $P['order_id']), array('delivery_note_status' => $set_delivery['status']));
                    $ret = _model('order_delivery_note')->update(array('order_id' => $P['order_id']), $set_delivery);
                    if ($ret) {
                        return_data(0, '操作成功', array('delivery_status' => $set_delivery['status']));
                    }
                }
                break;
            case 'accept':
                // 审核

                // 白条支付
                if ($order_detail['is_ious'] === '1') {
                    //获取店铺名称
                    $store_title = store_helper::get_store_title($order_detail['store_id']);

                    // 已上传, 未回款, 已预审, 返还余额
                    if ($order_delivery_note['status'] === '5') {

                        // 置 => 送货单状态为已审核
                        $set_delivery['status'] = '2';

                        // 下发余额
                        if ($order_delivery_note['is_return_cash'] != 1) {
                            $return_cash = $order_delivery_note['return_cash'];

                            //$extra = '白条支付返还，金额 ' . $return_cash . ';';
                            //修改备注文案 author:xiaolin date:2016-10-31
                            $extra = $store_title . '回款返还，金额 ' . $return_cash . ';';

                            // user_id: 合伙人
                            $res = user_money_helper::change_user_money(array(
                                'user_id' => $order_detail['agency_id'],
                                'user_money' => $return_cash,
                                'order_id' => $order_detail['id'],
                                'store_id' => $order_detail['store_id'],
                                'res_id' => user_money_config::RES_TYPE_IOUS_RETURN,
                                'admin_id' => user_helper::get_user_id(),
                                'extra' => $extra,
                            ));

                            if (!$res) {
                                return_data(1, '余额下发失败，请稍后重试');
                            }

                            $set_delivery['return_cash_time'] = datetime(); // 下发余额时间
                            $set_delivery['is_return_cash'] = 1; // 标识已下发余额
                        }
                    }

                    // 已上传, 已回(影院)/付(普通门店)款, 已审过(影院), 返还抱抱币
                    if ($order_delivery_note['status'] === '2' ||
                        ($order_delivery_note['status'] === '5' && $order_detail['is_pay'] === '1')
                    ) {
                        // 置 => 送货单状态为完成
                        $set_delivery['status'] = '4';

                        // 下发抱抱币
                        if ($order_delivery_note['is_return_bbcoin'] != 1) {
                            $return_bbcoin = $order_delivery_note['return_bbcoin'];
                            //$extra = '白条自动返还，数量 ' . $return_bbcoin . ';';
                            //修改备注文案 author:xiaolin date:2016-10-31
                            $extra = $store_title . '回款返还，数量 ' . $return_bbcoin . ';';

                            if (is_numeric($P['changed_bbcoin'])) {
                                if (trim($P['changed_reason']) == '') {
                                    return_data(1, '抱抱币更改理由不能为空');
                                }
                                $return_bbcoin = $P['changed_bbcoin'];
                                $extra .= ' 变更为: ' . $return_bbcoin . '; 变更备注: ' . $P['changed_reason'];
                            }

                            // user_id: 合伙人
                            $res = bbcoin_helper::change_bbcoin(array(
                                'user_id' => $order_detail['agency_id'],
                                'bbcoin' => $return_bbcoin,
                                'order_id' => $order_detail['id'],
                                'store_id' => $order_detail['store_id'],
                                'res_id' => bbcoin_config::RES_TYPE_IOUS_RETURN,
                                'admin_id' => user_helper::get_user_id(),
                                'extra' => $extra,
                            ));

                            if (!$res) {
                                return_data(1, '抱抱币下发失败，请稍后重试');
                            }
                            $set_delivery['return_bbcoin'] = $return_bbcoin; // 实际下发的抱抱币
                            $set_delivery['return_bbcoin_time'] = datetime(); // 下发的抱抱币时间
                            $set_delivery['is_return_bbcoin'] = 1; // 标识已下发抱抱币
                        }

                    }

                    if ($order_delivery_note['status'] === '5') {
                        // 置 => 送货单状态为已审核
                        // $set_delivery['status'] = '2';
                        // 审核时间
                        $set_delivery['verify_time'] = datetime();
                    }

                    if ($order_delivery_note['status'] === '2') {
                        // 置 => 状态为已支付
                        $set_order['is_pay'] = '1';
                        $set_order['pay_time'] = datetime();
                        $ret = _model('order')->update(array('id' => $P['order_id']), $set_order);
                        if (!$ret) {
                            return_data(1, '操作失败，无法设置支付状态');
                        }
                    }
                } else { // 影院的, 单独审核, 直接过
                    $set_delivery['status'] = '4';
                    $set_delivery['verify_time'] = datetime();
                }

                if (count($set_delivery)) {
                    _model('order')->update(array('id' => $P['order_id']), array('delivery_note_status' => $set_delivery['status']));
                    $ret = _model('order_delivery_note')->update(array('order_id' => $P['order_id']), $set_delivery);
                    if ($ret) {
                        return_data(0, '操作成功', array('delivery_status' => $set_delivery['status']));
                        // TODO 发送短信
                    }
                    return_data(1, '操作失败，请稍后重试');
                }

                break;

            case 'reject':
                $P['reject_reason'] = trim($P['reject_reason']);
                if (!$P['reject_reason']) {
                    return_data(1, '驳回理由不能为空');
                }
                // 驳回
                $set_delivery['reject_reason'] = $P['reject_reason'];
                $set_delivery['status'] = '3';
                $set_delivery['verify_time'] = datetime();

                _model('order')->update(array('id' => $P['order_id']), array('delivery_note_status' => $set_delivery['status']));
                $ret = _model('order_delivery_note')->update(array('order_id' => $P['order_id']), $set_delivery);
                if ($ret) {
                    return_data(0, '驳回送货单成功', array('delivery_status' => $set_delivery['status']));
                    // TODO 发送短信
                }

                return_data(1, '驳回失败，请稍后重试');
                break;
        }

        return_data(1, '无效的操作');

        // 未审核
    }

}

?>
